package net.thxjj.mobileServer.service.impl;

import com.alibaba.fastjson.JSONObject;
import net.thxjj.mobileServer.dao.GenieOauthDao;
import net.thxjj.mobileServer.dao.RelationDao;
import net.thxjj.mobileServer.dao.UserDao;
import net.thxjj.mobileServer.entity.*;
import net.thxjj.mobileServer.service.IGenieService;
import net.thxjj.mobileServer.util.JWTUtils;
import net.thxjj.mobileServer.util.ParameterMap;
import net.thxjj.mobileServer.util.SHA;
import net.thxjj.mobileServer.util.Tools;
import net.thxjj.sitermodel.MobileUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

@Service
public class GenieService implements IGenieService {
    private static final Logger logger = Logger.getLogger(GenieService.class.getCanonicalName());


    @Autowired
    private RelationDao relationDao;

    @Autowired
    private GenieOauthDao genieOauthDao;

    @Override
    public GenieOauthBean getGenieOauthBeanCode(String code,String refresh_token) {
        return genieOauthDao.getGenieOauth(code,refresh_token);
    }

    @Override
    public GenieOauthBean getGenieOauthBean(String access_token) {
        return genieOauthDao.getGenieOauthByAcccessToken(access_token);
    }

    @Override
    public HashMap<String, Object> updateAccessToken(String grant_type, GenieOauthBean genieOauthBean) {
        try {


            if("refresh_token".equals(grant_type)){
                long cur_time = System.currentTimeMillis();

                ParameterMap parameterMap_acc = new ParameterMap();
                parameterMap_acc.put("user_id",genieOauthBean.getUserId());
                parameterMap_acc.put("login_time",cur_time);
                parameterMap_acc.put("expired",cur_time+GenieResum.ACCESS_TOKEN_EXPIRED_SECOND);
                String ad = JSONObject.toJSON(parameterMap_acc).toString();
                String access_token =  JWTUtils.ProduceToken(ad);

                genieOauthDao.updateAccessToken(genieOauthBean.getId(),access_token,cur_time);

                HashMap<String, Object> result2 = new HashMap<String, Object>();
                result2.put("expires_in", GenieResum.ACCESS_TOKEN_EXPIRED_SECOND);
                result2.put("refresh_token",genieOauthBean.getRefreshToken());
                result2.put("access_token",access_token);

                return result2;
            }else{
                HashMap<String, Object> result = new HashMap<String, Object>();
                result.put("expires_in", GenieResum.ACCESS_TOKEN_EXPIRED_SECOND);
                result.put("refresh_token",genieOauthBean.getRefreshToken());
                result.put("access_token",genieOauthBean.getAccessToken());
                return result;
            }


        }catch (Exception e){
            e.printStackTrace();
            return ResponseModel.getGenieErrorCode(GenieErrcode.FAILED);
        }


    }

    @Override
    public HashMap<String, Object> loginOauthGenie(String username, String password,String redict_uri) {

        if(Tools.isEmpty(username)){
            return ResponseModel.getModel(GenieErrcode.USERNAME_IS_EMPTY,null);
        }else if(Tools.isEmpty(password)){
            return ResponseModel.getModel(GenieErrcode.PASSWORD_IS_EMPTY,null);
        }else {

            long count_username = genieOauthDao.getCountbyUsername(username);

            if(count_username<=0){
                return ResponseModel.getModel(GenieErrcode.USER_IS_NOT_EXIST,null);
            }else if(count_username>1){
                return ResponseModel.getModel(GenieErrcode.USER_IS_MORE_THAN_ONE,null);
            }else {
                try {
                    password = SHA.encryptSHA(password);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                MobileUser mobileUser = genieOauthDao.getUserBean(username,password,null);
                if(mobileUser==null){
                    return ResponseModel.getModel(GenieErrcode.PASSWORD_ERROR,null);
                }else{
                   String code = Tools.randomCharData(16);
                   long curTime = System.currentTimeMillis();

                    //生成access_token
                    String access_token = "";
                    ParameterMap parameterMap_acc = new ParameterMap();
                    parameterMap_acc.put("user_id",mobileUser.getUserId());
                    parameterMap_acc.put("username",username);
                    parameterMap_acc.put("login_time",curTime);
                    parameterMap_acc.put("expired",curTime+GenieResum.ACCESS_TOKEN_EXPIRED_SECOND);
                    String ad = JSONObject.toJSON(parameterMap_acc).toString();
                    try {
                        access_token =  JWTUtils.ProduceToken(ad);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    //生成refresh_token
                    String refresh_token = "";
                    ParameterMap parameterMap_acc2 = new ParameterMap();
                    parameterMap_acc2.put("user_id",mobileUser.getUserId());
                    parameterMap_acc2.put("username",username);
                    parameterMap_acc2.put("login_time",curTime);
                    parameterMap_acc2.put("expired",curTime+GenieResum.REFRESH_TOKEN_EXPIRED_SECOND);
                    String ad2 = JSONObject.toJSON(parameterMap_acc2).toString();
                    try {
                       refresh_token =  JWTUtils.ProduceToken(ad2);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    GenieOauthBean genieOauthBean = new GenieOauthBean();
                    genieOauthBean.setUserId(mobileUser.getUserId());
                    genieOauthBean.setCode(code);
                    genieOauthBean.setAccessToken(access_token);
                    genieOauthBean.setRefreshToken(refresh_token);
                    genieOauthBean.setLoginTime(curTime);
                    genieOauthBean.setRefreshTime(curTime);

                    genieOauthDao.addOauthBean(genieOauthBean);

                    String red = redict_uri + "&code=" + code;

                    return ResponseModel.getModel(GenieErrcode.SUCCESS,red);
                }
            }
        }
    }

    @Override
    public HashMap<String, Object> loginOauthEcho(String username, String password, String redict_uri, String state) {
        if(Tools.isEmpty(username)){
            return ResponseModel.getModel(GenieErrcode.USERNAME_IS_EMPTY,null);
        }else if(Tools.isEmpty(password)){
            return ResponseModel.getModel(GenieErrcode.PASSWORD_IS_EMPTY,null);
        }else {

            long count_username = genieOauthDao.getCountbyUsername(username);

            if(count_username<=0){
                return ResponseModel.getModel(GenieErrcode.USER_IS_NOT_EXIST,null);
            }else if(count_username>1){
                return ResponseModel.getModel(GenieErrcode.USER_IS_MORE_THAN_ONE,null);
            }else {
                try {
                    password = SHA.encryptSHA(password);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                MobileUser mobileUser = genieOauthDao.getUserBean(username,password,null);
                if(mobileUser==null){
                    return ResponseModel.getModel(GenieErrcode.PASSWORD_ERROR,null);
                }else{
                    String code = Tools.randomCharData(16);
                    long curTime = System.currentTimeMillis();

                    //生成access_token
                    String access_token = "";
                    ParameterMap parameterMap_acc = new ParameterMap();
                    parameterMap_acc.put("user_id",mobileUser.getUserId());
                    parameterMap_acc.put("username",username);
                    parameterMap_acc.put("login_time",curTime);
                    parameterMap_acc.put("expired",curTime+GenieResum.ACCESS_TOKEN_EXPIRED_SECOND);
                    String ad = JSONObject.toJSON(parameterMap_acc).toString();
                    try {
                        access_token =  JWTUtils.ProduceToken(ad);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    //生成refresh_token
                    String refresh_token = "";
                    ParameterMap parameterMap_acc2 = new ParameterMap();
                    parameterMap_acc2.put("user_id",mobileUser.getUserId());
                    parameterMap_acc2.put("username",username);
                    parameterMap_acc2.put("login_time",curTime);
                    parameterMap_acc2.put("expired",curTime+GenieResum.REFRESH_TOKEN_EXPIRED_SECOND);
                    String ad2 = JSONObject.toJSON(parameterMap_acc2).toString();
                    try {
                        refresh_token =  JWTUtils.ProduceToken(ad2);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    GenieOauthBean genieOauthBean = new GenieOauthBean();
                    genieOauthBean.setUserId(mobileUser.getUserId());
                    genieOauthBean.setCode(code);
                    genieOauthBean.setAccessToken(access_token);
                    genieOauthBean.setRefreshToken(refresh_token);
                    genieOauthBean.setLoginTime(curTime);
                    genieOauthBean.setRefreshTime(curTime);

                    genieOauthDao.addOauthBean(genieOauthBean);

                    String red = redict_uri + "?code=" + code + "&state="+state;

                    return ResponseModel.getModel(GenieErrcode.SUCCESS,red);
                }
            }
        }
    }

    @Override
    public List<String> getDeviceList(long user_id) {
        return relationDao.getUserBindDeviceList(user_id);
    }

    @Override
    public long getPowerState(String deviceId) {
        DeviceLog deviceLog = genieOauthDao.getDevLogSocketStatus(deviceId);
        if(deviceLog==null){
            return 0;
        }else{
            if(deviceLog.getContent().contains("\"powerstate\":1")){
                return 1;
            }else{
                return 0;
            }
        }
    }

}
